


package ciicos.check.controller;

import ciicos.base.ActionResult;
import ciicos.base.UserInfo;
import ciicos.base.vo.PageListVO;
import ciicos.base.vo.PaginationVO;
import ciicos.check.entity.CheckTaskEntity;
import ciicos.check.entity.CheckTaskItemEntity;
import ciicos.check.model.checktask.CheckTaskForm;
import ciicos.check.model.checktask.CheckTaskInfoVO;
import ciicos.check.model.checktask.CheckTaskItemModel;
import ciicos.check.model.checktask.CheckTaskListVO;
import ciicos.check.model.checktask.CheckTaskPagination;
import ciicos.check.service.CheckTaskItemService;
import ciicos.check.service.CheckTaskService;
import ciicos.config.ConfigValueUtil;
import ciicos.equ.entity.EquBaseEntity;
import ciicos.equ.entity.EquPointEntity;
import ciicos.exception.DataException;
import ciicos.permission.entity.UserEntity;
import ciicos.equ.service.EquBaseService;
import ciicos.equ.service.EquPointService;
import ciicos.util.DateUtil;
import ciicos.util.GeneraterSwapUtil;
import ciicos.util.JsonUtil;
import ciicos.util.RandomUtil;
import ciicos.util.StringUtil;
import ciicos.util.TenantUtil;
import ciicos.util.UserProvider;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;


/**
 * 巡检任务
 *
 * @版本： V3.2.0
 * @版权：
 * @作者： 产研项目租
 * @日期： 2023-07-26
 */
@Slf4j
@RestController
@Api(tags = "巡检任务", value = "checkManage")
@RequestMapping("/api/checkManage/CheckTask")
public class CheckTaskController {


    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private CheckTaskService checkTaskService;

    @Autowired
    private CheckTaskItemService checkTaskItemService;


    @Autowired
    private CheckPlanController checkPlanController;


    /*
     *   自动同步实时数据点位值
     * */
    @GetMapping("/syncRealDataPointValues/{id}")
    public ActionResult syncRealDataPointValues(@PathVariable("id") String id) {

        try {
            List<CheckTaskItemEntity> checkTaskPointEntities = checkTaskService.syncRealDataPointValues(id);

            List<CheckTaskItemModel> jsonToList = JsonUtil.getJsonToList(checkTaskPointEntities, CheckTaskItemModel.class);

            for (CheckTaskItemModel item : jsonToList) {
                if (StringUtil.isNotEmpty(item.getName())) {
                    String type = item.getType();
                    item.setType(generaterSwapUtil.getDicName(type, "529564962180304773"));
                    if ("1".equals(type)) {
                        item.setName(equBaseService.getInfo(item.getName()).getName());
                    } else if ("2".equals(type)) {
                        Map<String, Object> checkPlanItemcheckidMap = new HashMap<>();
                        item.setName(generaterSwapUtil.getPopupSelectValue("529327550036447045", "F_Id", "F_Name", (String) item.getName(), checkPlanItemcheckidMap, "[]", 1, null));
                    }
                }

                //编码转名称
                List<EquPointEntity> points = equPointService.list(new LambdaQueryWrapper<EquPointEntity>().eq(EquPointEntity::getCode, item.getPointName()));
                if (points != null && points.size() != 0) {
                    item.setPointName_name(points.get(0).getName());
                }

            }

            return ActionResult.success("同步成功", jsonToList);

        } catch (Exception e) {
            e.printStackTrace();
            return ActionResult.fail(e.getMessage());

        }
    }


    /**
     * 巡检任务确认操作
     */
    @PostMapping("/confirmOperation")
    public ActionResult confirmOperation(@RequestBody CheckTaskForm checkTaskForm) {
        CheckTaskEntity subentity = JsonUtil.getJsonToBean(checkTaskForm, CheckTaskEntity.class);
        CheckTaskEntity entity = checkTaskService.getInfo(checkTaskForm.getId());
        UserInfo userInfo = userProvider.get();
        if (entity != null) {
            subentity.setConfirmtime(new Date());
            subentity.setConfirmuserid(userInfo.getUserId());
            checkTaskService.updateById(subentity);

            return ActionResult.success("确认成功");
        } else {
            return ActionResult.fail("确认失败，数据不存在");
        }
    }

    /**
     * 列表
     *
     * @param checkTaskPagination
     * @return
     */
    @ApiOperation("获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody CheckTaskPagination checkTaskPagination) throws IOException {
        //树形判断是否有参数，有参数不造树
        List<CheckTaskEntity> list = checkTaskService.getList(checkTaskPagination);
        //处理id字段转名称，若无需转或者为空可删除
        List<CheckTaskListVO> listVO = JsonUtil.getJsonToList(list, CheckTaskListVO.class);
        for (CheckTaskListVO checkTaskVO : listVO) {
            checkTaskVO.setCreatortime_name(checkTaskVO.getCreatortime());
            checkTaskVO.setLastmodifytime_name(checkTaskVO.getLastmodifytime());
            checkTaskVO.setPlancode_name(checkTaskVO.getPlancode());
            checkTaskVO.setPlanname_name(checkTaskVO.getPlanname());
            checkTaskVO.setNeeduser_name(checkTaskVO.getNeeduser());
            checkTaskVO.setNeedtime_name(checkTaskVO.getNeedtime());
            checkTaskVO.setRealtime_name(checkTaskVO.getRealtime());
            checkTaskVO.setErrormax_name(checkTaskVO.getErrormax());
            checkTaskVO.setErrormin_name(checkTaskVO.getErrormin());
            checkTaskVO.setCheckteam_name(generaterSwapUtil.comSelectValues(checkTaskVO.getCheckteam(), false));
            checkTaskVO.setCode_name(checkTaskVO.getCode());
            //巡检项总数
            checkTaskVO.setItemtotals_name(checkTaskVO.getItemtotals());
            //巡检项异常数
            checkTaskVO.setItemanomalys_name(checkTaskVO.getItemanomalys());
            //巡检项完成数
            checkTaskVO.setItemfinisheds_name(checkTaskVO.getItemfinisheds());
            // 任务状态
            checkTaskVO.setStatus_name(generaterSwapUtil.getDicName(checkTaskVO.getStatus(), "534742730186692805"));
            // 确认结果
            checkTaskVO.setConfirmresult_name(generaterSwapUtil.getDicName(checkTaskVO.getConfirmresult(), "530036686470517573"));

            checkTaskVO.setConfirmuserid_name(generaterSwapUtil.userSelectValues(checkTaskVO.getConfirmuserid()));
            checkTaskVO.setConfirmtime_name(checkTaskVO.getConfirmtime() != null ? new Date(checkTaskVO.getConfirmtime()) : null);
            checkTaskVO.setTaskstarttime_name(checkTaskVO.getTaskstarttime() != null ? new Date(checkTaskVO.getTaskstarttime()) : null);
            checkTaskVO.setTaskendtime_name(checkTaskVO.getTaskendtime() != null ? new Date(checkTaskVO.getTaskendtime()) : null);
            checkTaskVO.setRealstarttime(checkTaskVO.getRealstarttime() != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Long.parseLong(checkTaskVO.getRealstarttime())) : null);
            checkTaskVO.setRealendtime(checkTaskVO.getRealendtime() != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Long.parseLong(checkTaskVO.getRealendtime())) : null);

            // 任务是否提前结束
            if (!StringUtil.isEmpty(checkTaskVO.getEndearly())) {
                if ("0".equals(checkTaskVO.getEndearly())) {
                    checkTaskVO.setEndearly_name("否");
                } else if ("1".equals(checkTaskVO.getEndearly())) {
                    checkTaskVO.setEndearly_name("是");
                }
            }
            checkTaskVO.setEndearlydesc_name(checkTaskVO.getEndearlydesc());

            // 处理执行人
            if (StringUtil.isNotEmpty(checkTaskVO.getActionusers())) {
                List<Map<String, Object>> userList = JsonUtil.getJsonToListMap(checkTaskVO.getActionusers());
                StringJoiner sj = new StringJoiner(",");
                for (Map<String, Object> user : userList) {
                    sj.add((String) user.get("username"));
                }
                checkTaskVO.setActionusers(sj.toString());
            }


        }

        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(checkTaskPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param checkTaskForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid CheckTaskForm checkTaskForm) throws DataException {
        String b = checkTaskService.checkForm(checkTaskForm, 0);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }
        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        checkTaskForm.setCreatoruserid(userInfo.getUserId());
        checkTaskForm.setCreatortime(DateUtil.getNow());
        checkTaskForm.setCode(generaterSwapUtil.getBillNumber("checkTaskCode", false));
        CheckTaskEntity entity = JsonUtil.getJsonToBean(checkTaskForm, CheckTaskEntity.class);
        entity.setId(mainId);
        checkTaskService.save(entity);
        if (checkTaskForm.getCheckTaskItemList() != null) {
            List<CheckTaskItemEntity> CheckTaskItemList = JsonUtil.getJsonToList(checkTaskForm.getCheckTaskItemList(), CheckTaskItemEntity.class);
            for (CheckTaskItemEntity entitys : CheckTaskItemList) {
                entitys.setId(RandomUtil.uuId());
                entitys.setParentid(entity.getId());

                checkTaskItemService.save(entitys);
            }
        }


        return ActionResult.success("创建成功");
    }

    @Autowired
    private EquPointService equPointService;

    /**
     * 信息
     *
     * @param id
     * @return
     */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<CheckTaskInfoVO> info(@PathVariable("id") String id) {
        CheckTaskEntity entity = checkTaskService.getInfo(id);
        CheckTaskInfoVO vo = JsonUtil.getJsonToBean(entity, CheckTaskInfoVO.class);
        vo.setCreatoruserid(generaterSwapUtil.userSelectValue(vo.getCreatoruserid()));
        if (vo.getCreatortime() != null) {
            vo.setCreatortime(vo.getCreatortime());
        }
        vo.setLastmodifyuserid(generaterSwapUtil.userSelectValue(vo.getLastmodifyuserid()));
        if (vo.getLastmodifytime() != null) {
            vo.setLastmodifytime(vo.getLastmodifytime());
        }
        int itemfinished = 0;

        //子表
        List<CheckTaskItemEntity> CheckTaskItemList = checkTaskService.getCheckTaskItemList(id);
        for (CheckTaskItemEntity checktaskitemEntity : CheckTaskItemList) {
            Map<String, Object> checkPlanItemcheckidMap = new HashMap<>();
            String type = checktaskitemEntity.getType();
            checktaskitemEntity.setType(generaterSwapUtil.getDicName(type, "529564962180304773"));
            if (StringUtil.isNotEmpty(checktaskitemEntity.getName())) {
                if ("1".equals(type)) {
                    EquBaseEntity info = equBaseService.getInfo(checktaskitemEntity.getName());
                    if (info != null) {
                        checktaskitemEntity.setName(info.getName());
                    }
                } else if ("2".equals(type)) {
                    checktaskitemEntity.setName(generaterSwapUtil.getPopupSelectValue("529327550036447045", "F_Id", "F_Name", (String) checktaskitemEntity.getName(), checkPlanItemcheckidMap, "[]", 1, null));
                }
            }
            if (StringUtil.isNotEmpty(checktaskitemEntity.getResult())) {
                itemfinished++;
            }

        }
        vo.setItemfinisheds(itemfinished);

        List<CheckTaskItemModel> items = JsonUtil.getJsonToList(CheckTaskItemList, CheckTaskItemModel.class);
        items.forEach(it -> {
            //编码转名称
            List<EquPointEntity> points = equPointService.list(new LambdaQueryWrapper<EquPointEntity>().eq(EquPointEntity::getCode, it.getPointName()));
            if (points != null && points.size() != 0) {
                it.setPointName_name(points.get(0).getName());
            }
        });
        vo.setCheckTaskItemList(items);
        //副表
        return ActionResult.success(vo);
    }

    @Autowired
    private EquBaseService equBaseService;

    /**
     * 表单信息(详情页)
     *
     * @param id
     * @return
     */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<CheckTaskInfoVO> detailInfo(@PathVariable("id") String id) {
        ActionResult info = info(id);
        Map<String, Object> dataMap = JsonUtil.entityToMap(info.getData());
        CheckTaskEntity entity = checkTaskService.getInfo(id);
        CheckTaskInfoVO vo = JsonUtil.getJsonToBean(entity, CheckTaskInfoVO.class);

        //子表数据转换
        List<CheckTaskItemEntity> checkTaskItemList = checkTaskService.getCheckTaskItemList(id);
        List<CheckTaskItemModel> checkTaskItemModelList = JsonUtil.getJsonToList(checkTaskItemList, CheckTaskItemModel.class);
        int checkTaskItemNum = 0;
        int itemfinished = 0;
        for (CheckTaskItemModel checkTaskItemModel : checkTaskItemModelList) {
            Map<String, Object> checkPlanItemcheckidMap = new HashMap<>();

            if (StringUtil.isNotEmpty(checkTaskItemModel.getName())) {
                if ("1".equals(checkTaskItemModel.getType())) {
                    checkTaskItemModel.setName(equBaseService.getInfo(checkTaskItemModel.getName()).getName());
                } else if ("2".equals(checkTaskItemModel.getType())) {
                    checkTaskItemModel.setName(generaterSwapUtil.getPopupSelectValue("529327550036447045", "F_Id", "F_Name", (String) checkTaskItemModel.getName(), checkPlanItemcheckidMap, "[]", checkTaskItemNum, dataMap));
                }
            }
            if (StringUtil.isNotEmpty(checkTaskItemModel.getResult())) {
                itemfinished++;
            }
            //编码转名称
            List<EquPointEntity> points = equPointService.list(new LambdaQueryWrapper<EquPointEntity>().eq(EquPointEntity::getCode, checkTaskItemModel.getPointName()));
            if (points != null && points.size() != 0) {
                checkTaskItemModel.setPointName(points.get(0).getName());
            }

            checkTaskItemModel.setType(generaterSwapUtil.getDicName(checkTaskItemModel.getType(), "529564962180304773"));
            checkTaskItemModel.setResult(generaterSwapUtil.getDicName(checkTaskItemModel.getResult(), "530036686470517573"));
            checkTaskItemModel.setAnomalyfinished(generaterSwapUtil.getDicName(checkTaskItemModel.getAnomalyfinished(), "530675554454612613"));
            checkTaskItemModel.setUnit(generaterSwapUtil.getDicName(checkTaskItemModel.getUnit(), "451016419769843781"));
            checkTaskItemNum++;
        }
        vo.setCheckTaskItemList(checkTaskItemModelList);
        vo.setItemfinisheds(itemfinished);


        vo.setCreatoruserid(generaterSwapUtil.userSelectValue(vo.getCreatoruserid()));
        vo.setLastmodifyuserid(generaterSwapUtil.userSelectValue(vo.getLastmodifyuserid()));
        vo.setCheckteam(generaterSwapUtil.comSelectValues(vo.getCheckteam(), false));
        vo.setStatus(generaterSwapUtil.getDicName(vo.getStatus(), "534742730186692805"));
        vo.setConfirmresult(generaterSwapUtil.getDicName(vo.getConfirmresult(), "453828504753012997"));
        vo.setConfirmuserid(generaterSwapUtil.userSelectValues(vo.getConfirmuserid()));
        vo.setFiles(generaterSwapUtil.getFileNameInJson(vo.getFiles()));

        // 处理执行人
        if (StringUtil.isNotEmpty(vo.getActionusers())) {
            List<Map<String, Object>> userList = JsonUtil.getJsonToListMap(vo.getActionusers());
            StringJoiner sj = new StringJoiner(",");
            for (Map<String, Object> user : userList) {
                sj.add((String) user.get("username"));
            }
            vo.setActionusers(sj.toString());
        }

        return ActionResult.success(vo);
    }

    @Autowired
    private CheckTaskAnomalyController checkTaskAnomalyController;

    /**
     * 更新
     *
     * @param id
     * @param repMap
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid Map<String, Object> repMap) throws DataException {
        CheckTaskForm checkTaskForm = JsonUtil.getJsonToBean(repMap, CheckTaskForm.class);
        String b = checkTaskService.checkForm(checkTaskForm, 1);
        if (StringUtil.isNotEmpty(b)) {
            return ActionResult.fail(b + "不能重复");
        }
        UserInfo userInfo = userProvider.get();
        CheckTaskEntity entity = checkTaskService.getInfo(id);
        if (entity != null) {
            checkTaskForm.setLastmodifyuserid(userInfo.getUserId());
            checkTaskForm.setLastmodifytime(DateUtil.getNow());
            checkTaskForm.setConfirmtime(DateUtil.getNow());
            checkTaskForm.setConfirmuserid(userInfo.getUserId());
            CheckTaskEntity subentity = JsonUtil.getJsonToBean(checkTaskForm, CheckTaskEntity.class);
            subentity.setStatus("2");

            if (subentity.getRealtime() != null) {
                subentity.setRealtime(Double.parseDouble(new DecimalFormat("#.0").format(subentity.getRealtime())));
            }

            boolean b1 = checkTaskService.updateById(subentity);
            if (!b1) {
                return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
            }

            int finished = 0;
            int anomaly = 0;

            //这里为防止添加条数或者减少条数所有全部删除再全部添加，移动端只编辑的情况下不会出现，所以不全部删除
            if (checkTaskForm.getCheckTaskItemList() != null) {
                List<CheckTaskItemEntity> CheckTaskItemList = JsonUtil.getJsonToList(checkTaskForm.getCheckTaskItemList(), CheckTaskItemEntity.class);
                for (CheckTaskItemEntity item : CheckTaskItemList) {
                    CheckTaskItemEntity info = checkTaskItemService.getInfo(item.getId());
                    info.setMin(item.getMin());
                    info.setMax(item.getMax());
                    info.setAnomalyfinished(item.getAnomalyfinished());
                    info.setResult(item.getResult());
                    info.setParentid(entity.getId());
                    info.setValue(item.getValue());
                    info.setAnomalydesc(item.getAnomalydesc());
                    checkTaskItemService.updateById(info);

                    if(StringUtil.isNotEmpty(info.getResult())){
                        //完成数
                        finished++;
                        if ("异常".equals(info.getResult())) {
                            //异常数
                            anomaly++;
                            checkTaskAnomalyController.create(info);
                        }
                    }

                }
                //更新数量统计
                subentity.setItemanomalys(anomaly);
                subentity.setItemfinisheds(finished);

                checkTaskService.updateById(subentity);
            }

            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        CheckTaskEntity entity = checkTaskService.getInfo(id);
        if (entity != null) {
            checkTaskService.delete(entity);
            QueryWrapper<CheckTaskItemEntity> queryWrapperCheckTaskItem = new QueryWrapper<>();
            queryWrapperCheckTaskItem.lambda().eq(CheckTaskItemEntity::getParentid, entity.getId());

            checkTaskItemService.remove(queryWrapperCheckTaskItem);
        }
        return ActionResult.success("删除成功");
    }


    @Autowired
    private TenantUtil tenantUtil;
    @Autowired
    protected ConfigValueUtil configValueUtil;

    /**
     * 生成今日任务
     *
     * @return
     */
    @XxlJob("checkCreateTask")
    @ApiOperation("生成今日任务")
    @GetMapping("/createTask")
    public ActionResult checkCreateTask() {
        try {
            if (configValueUtil.isMultiTenancy()) {
                //获取租户列表
                List<String> tenantCodes = tenantUtil.list();
                for (String code : tenantCodes) {
                    UserInfo userInfo = userProvider.get();
                    if (StringUtil.isNotEmpty(code)) {
                        userInfo.setUserAccount(code + "@admin");
                    } else {
                        userInfo.setUserAccount("admin");
                    }
                    //切换租户
                    tenantUtil.switchTenant(userInfo);
                    checkTaskService.createTask();
                }
            } else {
                checkTaskService.createTask();
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return ActionResult.success();
    }
}
